package com.taihua_tech.basic.exception;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.taihua_tech.basic.util.DataParam;

@RestControllerAdvice
public class MyExceptionHandler {

	private static Logger logger = Logger.getLogger(MyExceptionHandler.class);
	
    /*@ExceptionHandler(value = Exception.class)
    public JSONObject exceptionHandler(HttpServletRequest request,Exception e) {
    	logger.error("**************本次异常记录开始**********************");
    	logger.error("异常类型:"+e);
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		logger.error("发生时间:"+dateString);
		logger.error("************************************");
		logger.error("**************本次异常记录结束**********************");
		
		JSONObject jsonObj=new JSONObject();
		jsonObj.put("result","fail" );
		jsonObj.put("message","出现错误");
        return jsonObj;
    }*/
    
    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
    	//将来在这里放一些初始化好的权限的东西
    	model.addAttribute("user","userObject"); 
        model.addAttribute("author", "Magical Sam");
    }
    
    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    	DataParam param=null;
    	if(binder.getTarget() instanceof DataParam){
    		param = (DataParam)binder.getTarget();
    		System.out.println("目标是param:::::::::::::::::::"+param);
    	}else{
    		System.out.println("目标非param=====================");
    	}
    }
}